package top.taven.http;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnDemo {
    public static void main(String[] args) {
        try{

            Demo1();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void Demo1() throws Exception {
        String targetURL = "https://4.ipw.cn";

        sendGetReq(targetURL);

    }

    public static void Demo2() throws Exception {
        String targetURL = "https://4.ipw.cn"; // 替换为你的目标URL
        String payloadFile = "send.txt"; //

        try (BufferedReader reader = new BufferedReader(new FileReader(payloadFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sendPostReq(targetURL, line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void sendGetReq(String targetURL) throws Exception {
        URL url = new URL(targetURL);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为GET
        connection.setRequestMethod("GET");

        // 获取响应码和内容
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            byte[] datas = connection.getInputStream().readAllBytes();
            System.out.println(new String(datas));
        }

        connection.disconnect();
    }

    private static void sendPostReq(String targetURL, String payload) throws Exception {
        URL url = new URL(targetURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        // 设置请求头，根据实际情况调整
        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //connection.setRequestProperty("Content-Length", Integer.toString(payload.getBytes().length));

        // 发送数据
        connection.getOutputStream().write(payload.getBytes());

        // 获取响应码和内容
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            byte[] datas = connection.getInputStream().readAllBytes();
            System.out.println(new String(datas));
        }

        connection.disconnect();
    }
}